<!DOCTYPE html>












  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">


















  
  
    
  
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.6/jquery.fancybox.min.css">







<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.1.1">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico?v=7.1.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico?v=7.1.1">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.1" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.1.1',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: true,
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="简介MyBatis 官网 是这么介绍它自己的：  MyBatis 是一款优秀的持久层框架，它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO（Plain Old Java Objects，普通老式 Java 对象）为数据库中的记">
<meta name="keywords" content="Spring Boot,MyBatis">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring Boot 实战 —— MyBatis（注解版）使用方法">
<meta property="og:url" content="https://michael728.github.io/2019/07/20/java-spring-boot-mybatis/index.html">
<meta property="og:site_name" content="Michael翔">
<meta property="og:description" content="简介MyBatis 官网 是这么介绍它自己的：  MyBatis 是一款优秀的持久层框架，它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO（Plain Old Java Objects，普通老式 Java 对象）为数据库中的记">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://b2.bmp.ovh/imgs/2019/07/5f37fc105fab759c.jpeg">
<meta property="og:image" content="https://b2.bmp.ovh/imgs/2019/07/8114562151cbc00f.jpg">
<meta property="og:updated_time" content="2020-01-05T15:47:56.120Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Spring Boot 实战 —— MyBatis（注解版）使用方法">
<meta name="twitter:description" content="简介MyBatis 官网 是这么介绍它自己的：  MyBatis 是一款优秀的持久层框架，它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO（Plain Old Java Objects，普通老式 Java 对象）为数据库中的记">
<meta name="twitter:image" content="https://b2.bmp.ovh/imgs/2019/07/5f37fc105fab759c.jpeg">



  <link rel="alternate" href="/atom.xml" title="Michael翔" type="application/atom+xml">



  
  
  <link rel="canonical" href="https://michael728.github.io/2019/07/20/java-spring-boot-mybatis/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Spring Boot 实战 —— MyBatis（注解版）使用方法 | Michael翔</title>
  






  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?1c9958c951d5a7661571422e0340e156";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>







  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

  <meta name="referrer" content="never">
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Michael翔</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">因上努力，果上随缘！</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tools">

    
    
    
      
    

    

    <a href="/tools/" rel="section"><i class="menu-item-icon fa fa-fw fa-location-arrow"></i> <br>利器</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-books">

    
    
    
      
    

    

    <a href="/books" rel="section"><i class="menu-item-icon fa fa-fw fa-book"></i> <br>阅读</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-movies">

    
    
    
      
    

    

    <a href="/movies" rel="section"><i class="menu-item-icon fa fa-fw fa-film"></i> <br>观影</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-think">

    
    
    
      
    

    

    <a href="/think" rel="section"><i class="menu-item-icon fa fa-fw fa-lightbulb-o"></i> <br>一言</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    
  
  

  

  <a href="https://github.com/michael728" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewbox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a>



    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://michael728.github.io/2019/07/20/java-spring-boot-mybatis/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Michael翔">
      <meta itemprop="description" content="DevOps CICD Blog 持续学习">
      <meta itemprop="image" content="/images/logo.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Michael翔">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Spring Boot 实战 —— MyBatis（注解版）使用方法

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-07-20 12:49:10" itemprop="dateCreated datePublished" datetime="2019-07-20T12:49:10+00:00">2019-07-20</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2020-01-05 15:47:56" itemprop="dateModified" datetime="2020-01-05T15:47:56+00:00">2020-01-05</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Java/" itemprop="url" rel="index"><span itemprop="name">Java</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://b2.bmp.ovh/imgs/2019/07/5f37fc105fab759c.jpeg" alt="MyBatis"></p>
<h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><p><a href="http://www.mybatis.org/mybatis-3/zh/index.html" target="_blank" rel="noopener">MyBatis 官网</a> 是这么介绍它自己的：</p>
<blockquote>
<p>MyBatis 是一款优秀的持久层框架，它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO（Plain Old Java Objects，普通老式 Java 对象）为数据库中的记录。</p>
</blockquote>
<a id="more"></a>
<h2 id="示例代码"><a href="#示例代码" class="headerlink" title="示例代码"></a>示例代码</h2><ul>
<li><a href="https://github.com/Michael728/awesome-spring-boot-examples" target="_blank" rel="noopener">awesome-spring-boot-examples</a></li>
</ul>
<h2 id="依赖"><a href="#依赖" class="headerlink" title="依赖"></a>依赖</h2><p>这里仅展示和 MyBatis 相关的数据库依赖项，完整的示例，请下载示例代码。</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&lt;!--mysql--&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;mysql&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.mybatis.spring.boot&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;mybatis-spring-boot-starter&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;2.1.0&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>
<p><code>spring-boot-start</code> 系列的包，真是给 Spring Boot 开发带来了极大的便利，它的项目地址是：</p>
<ul>
<li><a href="https://github.com/mybatis/spring-boot-starter" target="_blank" rel="noopener">Github-mybatis/spring-boot-starter</a></li>
<li><a href="http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/" target="_blank" rel="noopener">官宣-What is MyBatis-Spring-Boot-Starter?</a> 推荐</li>
</ul>
<h2 id="配置"><a href="#配置" class="headerlink" title="配置"></a>配置</h2><p>创建 <code>users</code> 表的 SQL：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SET</span> FOREIGN_KEY_CHECKS=<span class="number">0</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">-- ----------------------------</span></span><br><span class="line"><span class="comment">-- Table structure for `users`</span></span><br><span class="line"><span class="comment">-- ----------------------------</span></span><br><span class="line"><span class="keyword">DROP</span> <span class="keyword">TABLE</span> <span class="keyword">IF</span> <span class="keyword">EXISTS</span> <span class="string">`users`</span>;</span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> <span class="string">`users`</span> (</span><br><span class="line">  <span class="string">`id`</span> <span class="built_in">bigint</span>(<span class="number">20</span>) <span class="keyword">NOT</span> <span class="literal">NULL</span> AUTO_INCREMENT <span class="keyword">COMMENT</span> <span class="string">'主键id'</span>,</span><br><span class="line">  <span class="string">`userName`</span> <span class="built_in">varchar</span>(<span class="number">32</span>) <span class="keyword">DEFAULT</span> <span class="literal">NULL</span> <span class="keyword">COMMENT</span> <span class="string">'用户名'</span>,</span><br><span class="line">  <span class="string">`passWord`</span> <span class="built_in">varchar</span>(<span class="number">32</span>) <span class="keyword">DEFAULT</span> <span class="literal">NULL</span> <span class="keyword">COMMENT</span> <span class="string">'密码'</span>,</span><br><span class="line">  <span class="string">`user_sex`</span> <span class="built_in">varchar</span>(<span class="number">32</span>) <span class="keyword">DEFAULT</span> <span class="literal">NULL</span>,</span><br><span class="line">  <span class="string">`nick_name`</span> <span class="built_in">varchar</span>(<span class="number">32</span>) <span class="keyword">DEFAULT</span> <span class="literal">NULL</span>,</span><br><span class="line">  PRIMARY <span class="keyword">KEY</span> (<span class="string">`id`</span>)</span><br><span class="line">) <span class="keyword">ENGINE</span>=<span class="keyword">InnoDB</span> AUTO_INCREMENT=<span class="number">28</span> <span class="keyword">DEFAULT</span> <span class="keyword">CHARSET</span>=utf8;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">-- ----------------------------</span></span><br><span class="line"><span class="comment">-- Records of sys_user</span></span><br><span class="line"><span class="comment">-- ----------------------------</span></span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> <span class="string">`users`</span> <span class="keyword">VALUES</span> (<span class="number">1</span>,<span class="string">'michael翔'</span>, <span class="string">'123'</span>, <span class="string">'MAN'</span>, <span class="string">'zx'</span>);</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> <span class="string">`users`</span> <span class="keyword">VALUES</span> (<span class="number">2</span>,<span class="string">'张小敬'</span>, <span class="string">'123'</span>, <span class="string">'MAN'</span>, <span class="string">'zxj'</span>);</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> <span class="string">`users`</span> <span class="keyword">VALUES</span> (<span class="number">3</span>,<span class="string">'李司辰'</span>, <span class="string">'123'</span>, <span class="string">'MAN'</span>, <span class="string">'lsc'</span>);</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> <span class="string">`users`</span> <span class="keyword">VALUES</span> (<span class="number">4</span>,<span class="string">'崔器'</span>, <span class="string">'123'</span>, <span class="string">'MAN'</span>, <span class="string">'cq'</span>);</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> <span class="string">`users`</span> <span class="keyword">VALUES</span> (<span class="number">5</span>,<span class="string">'姚汝能'</span>, <span class="string">'123'</span>, <span class="string">'MAN'</span>, <span class="string">'yrn'</span>);</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> <span class="string">`users`</span> <span class="keyword">VALUES</span> (<span class="literal">null</span>,<span class="string">'檀棋'</span>, <span class="string">'123'</span>, <span class="string">' WOMAN'</span>, <span class="string">'tq'</span>);</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> <span class="string">`users`</span> (<span class="string">`userName`</span>,<span class="string">`passWord`</span>,<span class="string">`user_sex`</span>,<span class="string">`nick_name`</span>) <span class="keyword">VALUES</span> (<span class="string">'michael'</span>, <span class="string">'123'</span>, <span class="string">'MAN'</span>, <span class="string">'zx'</span>);</span><br></pre></td></tr></table></figure>
<p>说明：</p>
<ul>
<li>id 设置的是自增，当插入数据时，可以不传或者传 <code>null</code> 值，都可以；</li>
<li>插入数据，可以指定 <code>column</code> 也可以不指定；</li>
</ul>
<p><code>application-dev.properties</code>：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">swagger.enable=true</span><br><span class="line">server.port=8081</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">spring.datasource.url=jdbc:mysql://192.168.3.43:3306/beta?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=true</span><br><span class="line">spring.datasource.username=root</span><br><span class="line">spring.datasource.password=123456</span><br><span class="line">spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver</span><br><span class="line"></span><br><span class="line">mybatis.type-aliases-package==com.michael.springbootmybatis.model</span><br><span class="line">mybatis.configuration.map-underscore-to-camel-case=true</span><br></pre></td></tr></table></figure>
<ul>
<li>配置驼峰属性自动映射，例如实体中属性为 <code>userSex</code>,数据库属性为 <code>user_sex</code>，MyBatis 默认是不能自动转换的。我们可以配置 <code>mybatis.configuration.map-underscore-to-camel-case</code> 实现自动映射。如果不进行此配置，通常我们要自定义以下结果集映射：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Results</span>(&#123;</span><br><span class="line">        <span class="meta">@Result</span>(property = <span class="string">"userSex"</span>, column = <span class="string">"user_sex"</span>),</span><br><span class="line">        <span class="meta">@Result</span>(property = <span class="string">"nickName"</span>, column = <span class="string">"nick_name"</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="meta">@Select</span>(<span class="string">"SELECT * FROM users WHERE id = #&#123;id&#125;"</span>)</span><br><span class="line"><span class="function">UserEntity <span class="title">getUserById</span><span class="params">(Long id)</span></span>;</span><br></pre></td></tr></table></figure>
<p>在很多 <code>Select</code> 语句需要做结果映射时，自然是相当麻烦。除了上面配置「驼峰属性自动映射」，也可以用在 <code>@Results</code> 中使用 <code>id</code> 来标识一个映射关系，然后可以用 <code>@ResultMap</code> 复用这个映射关系：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Select</span>(<span class="string">"SELECT * FROM users"</span>)</span><br><span class="line"><span class="meta">@Results</span>(id = <span class="string">"user"</span>, value = &#123;</span><br><span class="line">        <span class="meta">@Result</span>(property = <span class="string">"userSex"</span>, column = <span class="string">"user_sex"</span>),</span><br><span class="line">        <span class="meta">@Result</span>(property = <span class="string">"nickName"</span>, column = <span class="string">"nick_name"</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="meta">@Select</span>(<span class="string">"SELECT * FROM users WHERE id = #&#123;id&#125;"</span>)</span><br><span class="line"><span class="function">List&lt;UserEntity&gt; <span class="title">getAll</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="meta">@ResultMap</span>(<span class="string">"user"</span>)</span><br><span class="line"><span class="meta">@Select</span>(<span class="string">"SELECT * FROM users WHERE id = #&#123;id&#125;"</span>)</span><br><span class="line"><span class="function">UserEntity <span class="title">getUserById</span><span class="params">(Integer id)</span></span>;</span><br></pre></td></tr></table></figure>
<h2 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h2><p>这里仅展示关键的部分的代码，完整可看下文的示例代码。</p>
<p>实体类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@ApiModel</span>(description = <span class="string">"UserEntity 实体类"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserEntity</span> <span class="keyword">implements</span> <span class="title">Serializable</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">1L</span>;</span><br><span class="line">    <span class="meta">@ApiModelProperty</span>(value = <span class="string">"用户 id"</span>, dataType = <span class="string">"Long"</span>)</span><br><span class="line">    <span class="keyword">private</span> Long id;</span><br><span class="line">    <span class="meta">@ApiModelProperty</span>(value = <span class="string">"用户名"</span>, required = <span class="keyword">true</span>)</span><br><span class="line">    <span class="keyword">private</span> String userName;</span><br><span class="line">    <span class="meta">@ApiModelProperty</span>(value = <span class="string">"密码"</span>)</span><br><span class="line">    <span class="keyword">private</span> String passWord;</span><br><span class="line">    <span class="meta">@ApiModelProperty</span>(value = <span class="string">"性别"</span>)</span><br><span class="line">    <span class="keyword">private</span> UserSexEnum userSex;</span><br><span class="line">    <span class="meta">@ApiModelProperty</span>(value = <span class="string">"昵称"</span>)</span><br><span class="line">    <span class="keyword">private</span> String nickName;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"userName "</span> + <span class="keyword">this</span>.userName + <span class="string">", password "</span> + <span class="keyword">this</span>.passWord + <span class="string">" , sex "</span> + <span class="keyword">this</span>.userSex;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>dao/mapper</code> 接口，数据库交互（<code>Data Access Object</code>）层：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserMapper</span> </span>&#123;</span><br><span class="line"><span class="comment">//    @Results(&#123;</span></span><br><span class="line"><span class="comment">//            @Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class),</span></span><br><span class="line"><span class="comment">//            @Result(property = "nickName", column = "nick_name")</span></span><br><span class="line"><span class="comment">//    &#125;)</span></span><br><span class="line">    <span class="meta">@Select</span>(<span class="string">"SELECT * FROM users"</span>)</span><br><span class="line">    <span class="function">Page&lt;UserEntity&gt; <span class="title">getAll</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//    @Results(&#123;</span></span><br><span class="line"><span class="comment">//            @Result(property = "userSex", column = "user_sex"),</span></span><br><span class="line"><span class="comment">//            @Result(property = "nickName", column = "nick_name")</span></span><br><span class="line"><span class="comment">//    &#125;)</span></span><br><span class="line">    <span class="meta">@Select</span>(<span class="string">"SELECT * FROM users WHERE id = #&#123;id&#125;"</span>)</span><br><span class="line">    <span class="function">UserEntity <span class="title">getUserById</span><span class="params">(Long id)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Insert</span>(<span class="string">"INSERT INTO users(userName, passWord, user_sex, nick_name) "</span> +</span><br><span class="line">            <span class="string">"VALUES(#&#123;userName&#125;, #&#123;passWord&#125;, #&#123;userSex&#125;, #&#123;nickName&#125;)"</span>)</span><br><span class="line">    <span class="meta">@Options</span>(useGeneratedKeys = <span class="keyword">true</span>, keyProperty = <span class="string">"id"</span>)</span><br><span class="line"><span class="comment">//   @SelectKey(statement = "select last_insert_id()", keyProperty = "id", before = false, resultType = Integer.class)</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">insert</span><span class="params">(UserEntity user)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Update</span>(<span class="string">"UPDATE users SET userName=#&#123;userName&#125;,nick_name=#&#123;nickName&#125; WHERE id = #&#123;id&#125;"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">update</span><span class="params">(UserEntity user)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Delete</span>(<span class="string">"DELETE FROM users WHERE id= #&#123;id&#125;"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">deleteUserById</span><span class="params">(Long id)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>说明：</p>
<ul>
<li><code>insert</code> 这里用了一个 <code>@Options</code> 的注解，实现了「主键回填」的功能，也就是说，再创建好一个 <code>user</code> 之后，<code>user</code> 请求体中的 <code>id</code> 属性会自动赋值好；</li>
<li><code>@SelectKey</code> 注解被注释掉了，这个注解也同样可以实现「主键回填」的功能；</li>
</ul>
<p>service 接口：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 查询所有用户</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">Map&lt;String,Object&gt; <span class="title">getAll</span><span class="params">(<span class="keyword">int</span> pageNum, <span class="keyword">int</span> pageSize)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据用户 ID 查询用户</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id 用户 ID</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">UserEntity <span class="title">getUserById</span><span class="params">(Long id)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 新增一个用户</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> user</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">insert</span><span class="params">(UserEntity user)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 更新用户信息，用户 ID 不传，会更新失败</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> user</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">String <span class="title">update</span><span class="params">(UserEntity user)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据用户 ID 删除用户</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">String <span class="title">deleteById</span><span class="params">(Long id)</span></span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>service 接口的实现类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserServiceImpl</span> <span class="keyword">implements</span> <span class="title">UserService</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserMapper userMapper;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Map&lt;String,Object&gt; <span class="title">getAll</span><span class="params">(<span class="keyword">int</span> pageNum, <span class="keyword">int</span> pageSize)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//将参数传给这个方法就可以实现物理分页了，非常简单。</span></span><br><span class="line">        PageHelper.startPage(pageNum, pageSize);</span><br><span class="line">        PageInfo&lt;UserEntity&gt; pageInfo = <span class="keyword">new</span> PageInfo&lt;&gt;(userMapper.getAll());</span><br><span class="line">        Long total = pageInfo.getTotal();</span><br><span class="line">        List&lt;UserEntity&gt; users = pageInfo.getList();</span><br><span class="line">        Map&lt;String,Object&gt; map = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">        map.put(<span class="string">"total"</span>, total);</span><br><span class="line">        map.put(<span class="string">"data"</span>, users);</span><br><span class="line">        <span class="keyword">return</span> map;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> UserEntity <span class="title">getUserById</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> userMapper.getUserById(id);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">insert</span><span class="params">(UserEntity user)</span> </span>&#123;</span><br><span class="line">        userMapper.insert(user);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">update</span><span class="params">(UserEntity user)</span> </span>&#123;</span><br><span class="line">        userMapper.update(user);</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"success"</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">deleteById</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">        userMapper.deleteUserById(id);</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"success"</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>controller 类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"/api/v1/"</span>)</span><br><span class="line"><span class="meta">@Api</span>(tags = &#123;<span class="string">"用户相关接口"</span>&#125;, value = <span class="string">"用户模块"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserController</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserService userService;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 查询全部用户</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@ApiOperation</span>(value = <span class="string">"获取用户列表"</span>, notes = <span class="string">"获取全部用户信息"</span>)</span><br><span class="line">    <span class="meta">@RequestMapping</span>(value = <span class="string">"/users"</span>, method = RequestMethod.GET)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Map&lt;String,Object&gt; <span class="title">getUsers</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">            @RequestParam(name = <span class="string">"pageNum"</span>, defaultValue = <span class="string">"1"</span>, required = <span class="keyword">false</span>)</span> <span class="keyword">int</span> pageNum,</span></span><br><span class="line"><span class="function">            @<span class="title">RequestParam</span><span class="params">(name = <span class="string">"pateSize"</span>, defaultValue = <span class="string">"2"</span>, required = <span class="keyword">false</span>)</span> <span class="keyword">int</span> pageSize) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> userService.getAll(pageNum, pageSize);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据用户 ID 查询用户</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@ApiOperation</span>(value = <span class="string">"查询单用户"</span>, notes = <span class="string">"根据用户id 查询其信息"</span>)</span><br><span class="line">    <span class="meta">@ApiImplicitParam</span>(name = <span class="string">"id"</span>, value = <span class="string">"用户id"</span>, paramType = <span class="string">"query"</span>, required = <span class="keyword">true</span>)</span><br><span class="line">    <span class="meta">@GetMapping</span>(<span class="string">"/user/&#123;id&#125;"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> UserEntity <span class="title">getUser</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">        UserEntity user = userService.getUserById(id);</span><br><span class="line">        <span class="keyword">return</span> user;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 存储用户信息</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> user</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@ApiOperation</span>(value = <span class="string">"存储用户信息"</span>, notes = <span class="string">"存储用户详细信息"</span>)</span><br><span class="line">    <span class="meta">@RequestMapping</span>(value = <span class="string">"/user"</span>, method = RequestMethod.POST)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">save</span><span class="params">(UserEntity user)</span> </span>&#123;</span><br><span class="line">        userService.insert(user);</span><br><span class="line">        <span class="comment">// 用到了 主键回填 的配置</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">"Create success, user id: "</span> + user.getId();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 更新用户信息</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> user</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@ApiOperation</span>(value = <span class="string">"更新用户信息"</span>, notes = <span class="string">"更新用户的个人信息"</span>)</span><br><span class="line">    <span class="meta">@PutMapping</span>(<span class="string">"/user/"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">update</span><span class="params">(@RequestBody UserEntity user)</span> </span>&#123;</span><br><span class="line">        userService.update(user);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据用户 ID 删除用户</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@ApiOperation</span>(value = <span class="string">"删除用户"</span>, notes = <span class="string">"根据用户id删除用户信息"</span>)</span><br><span class="line">    <span class="meta">@ApiImplicitParams</span>(&#123;</span><br><span class="line">            <span class="meta">@ApiImplicitParam</span>(name = <span class="string">"id"</span>, value = <span class="string">"用户id"</span>, required = <span class="keyword">true</span>, paramType = <span class="string">"path"</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="meta">@RequestMapping</span>(value = <span class="string">"/user/&#123;id&#125;"</span>, method = RequestMethod.DELETE)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">delete</span><span class="params">(@PathVariable(<span class="string">"id"</span>)</span> Long id) </span>&#123;</span><br><span class="line">        userService.deleteById(id);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>启动类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="meta">@MapperScan</span>(<span class="string">"com.michael.springbootmybatis.mapper"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SpringBootMybatisApplication</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        SpringApplication.run(SpringBootMybatisApplication.class, args);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><code>@MapperScan(&quot;com.winter.mapper&quot;)</code> 这个注解非常的关键，这个对应了项目中 <code>mapper/dao</code> 所对应的包路径。</li>
<li>如果不用上面的方式，就需要在每个 <code>mapper/dao</code> 类上使用 <code>@Mapper</code> 注解；</li>
</ul>
<h2 id="分页"><a href="#分页" class="headerlink" title="分页"></a>分页</h2><p>通常，在进行查询时，我们为了避免一次性返回所有结果，造成接口响应慢等问题。通常会进行分页。比如查询所有用户的接口，实际应用中，用户数据可能会很多，如果全部一次返回，明显不合适。这时候，就需要进行分页查询。</p>
<p>本文我们选用插键 <code>pagehelper-spring-boot-starter</code> 要进行分页。</p>
<h3 id="添加依赖"><a href="#添加依赖" class="headerlink" title="添加依赖"></a>添加依赖</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- 分页插件 --&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;com.github.pagehelper&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;pagehelper-spring-boot-starter&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;1.2.5&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>
<h3 id="分页配置"><a href="#分页配置" class="headerlink" title="分页配置"></a>分页配置</h3><p>需要添加相应的配置：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span>pagehelper分页插件</span><br><span class="line">pagehelper.helperDialect=mysql</span><br><span class="line">pagehelper.reasonable=true</span><br><span class="line">pagehelper.supportMethodsArguments=true</span><br><span class="line">pagehelper.params=count=countSql</span><br><span class="line">pagehelper.row-bounds-with-count=true</span><br><span class="line">pageSizeZero=true</span><br></pre></td></tr></table></figure>
<p>分页插键参数介绍：</p>
<ul>
<li><code>helperDialect</code>：分页插件会自动检测当前的数据库链接，自动选择合适的分页方式</li>
<li><code>reasonable</code>：分页合理化参数，默认值为 false。当该参数设置为 true 时，<code>pageNum&lt;=0</code> 时会查询第一页， <code>pageNum&gt;pages</code>（超过总数时），会查询最后一页。默认 false 时，直接根据参数进行查询</li>
<li><code>params</code>：为了支持 <code>startPage(Object params)</code> 方法，增加了该参数来配置参数映射，用于从对象中根据属性名取值， 可以配置 <code>pageNum,pageSize,count,pageSizeZero,reasonable</code>，不配置映射的用默认值， 默认值为 <code>pageNum=pageNum;pageSize=pageSize;count=countSql;reasonable=reasonable;pageSizeZero=pageSizeZero</code>。</li>
<li><code>supportMethodsArguments</code>：支持通过 Mapper 接口参数来传递分页参数，默认值 false，分页插件会从查询方法的参数值中，自动根据上面 <code>params</code> 配置的字段中取值，查找到合适的值时就会自动分页</li>
<li><code>pageSizeZero</code>：默认值为 false，当该参数设置为 true 时，如果 <code>pageSize=0</code> 或者 <code>RowBounds.limit = 0</code> 就会查询出全部的结果（相当于没有执行分页查询，但是返回结果仍然是 Page 类型）。我测试时，发现不设置，<code>pageSize=0</code> 也会返回全部；</li>
</ul>
<h3 id="代码变动"><a href="#代码变动" class="headerlink" title="代码变动"></a>代码变动</h3><p><code>mapper</code> 中查找全部用户的方法改成如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Select</span>(<span class="string">"SELECT * FROM users"</span>)</span><br><span class="line"><span class="function">Page&lt;UserEntity&gt; <span class="title">getAll</span><span class="params">()</span></span>;</span><br></pre></td></tr></table></figure>
<p>service 接口和其实现类的方法改成：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">PageInfo&lt;UserEntity&gt; <span class="title">getAll</span><span class="params">(<span class="keyword">int</span> pageNum, <span class="keyword">int</span> pageSize)</span></span>;</span><br></pre></td></tr></table></figure>
<p>service 接口实现类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> PageInfo&lt;UserEntity&gt; <span class="title">getAll</span><span class="params">(<span class="keyword">int</span> pageNum, <span class="keyword">int</span> pageSize)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//将参数传给这个方法就可以实现物理分页了，非常简单。</span></span><br><span class="line">    PageHelper.startPage(pageNum, pageSize);</span><br><span class="line">    PageInfo&lt;UserEntity&gt; pageInfo = <span class="keyword">new</span> PageInfo&lt;&gt;(userMapper.getAll());</span><br><span class="line">    <span class="keyword">return</span> pageInfo;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>注意点：</p>
<ul>
<li><code>PageHelper.startPage(pageNo,pageSize);</code> 只对其后的第一个查询有效；</li>
</ul>
<p>controller 类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@ApiOperation</span>(value = <span class="string">"获取用户列表"</span>, notes = <span class="string">"获取全部用户信息"</span>)</span><br><span class="line"><span class="meta">@RequestMapping</span>(value = <span class="string">"/users"</span>, method = RequestMethod.GET)</span><br><span class="line"><span class="function"><span class="keyword">public</span> PageInfo&lt;UserEntity&gt; <span class="title">getUsers</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        @RequestParam(name = <span class="string">"pageNum"</span>, defaultValue = <span class="string">"1"</span>, required = <span class="keyword">false</span>)</span> <span class="keyword">int</span> pageNum,</span></span><br><span class="line"><span class="function">        @<span class="title">RequestParam</span><span class="params">(name = <span class="string">"pateSize"</span>, defaultValue = <span class="string">"2"</span>, required = <span class="keyword">false</span>)</span> <span class="keyword">int</span> pageSize) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> userService.getAll(pageNum, pageSize);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><img src="https://b2.bmp.ovh/imgs/2019/07/8114562151cbc00f.jpg" alt="分页"></p>
<h3 id="进一步"><a href="#进一步" class="headerlink" title="进一步"></a>进一步</h3><p>上面的分页结果返回的内容有点多，一些属性并不想放在返回体中。可以进一步优化。编写工具类限定关心的属性。</p>
<p>分页查询结果封装类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PageResult</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 当前页码</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> pageNum;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 每页数量</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> pageSize;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 记录总数</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">long</span> totalSize;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 页码总数</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> totalPages;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 数据模型</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> List&lt;?&gt; content;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>分页查询工具类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PageUitls</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 将分页信息封装到统一的接口</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> pageInfo</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> PageResult <span class="title">getPageResult</span><span class="params">(PageInfo&lt;?&gt; pageInfo)</span> </span>&#123;</span><br><span class="line">        PageResult pageResult = <span class="keyword">new</span> PageResult();</span><br><span class="line">        pageResult.setPageNum(pageInfo.getPageNum());</span><br><span class="line">        pageResult.setPageSize(pageInfo.getPageSize());</span><br><span class="line">        pageResult.setTotalSize(pageInfo.getTotal());</span><br><span class="line">        pageResult.setTotalPages(pageInfo.getPages());</span><br><span class="line">        pageResult.setContent(pageInfo.getList());</span><br><span class="line">        <span class="keyword">return</span> pageResult;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>接口方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">  * 查询所有用户</span></span><br><span class="line"><span class="comment">  *</span></span><br><span class="line"><span class="comment">  * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"><span class="function">PageResult <span class="title">getAll</span><span class="params">(<span class="keyword">int</span> pageNum, <span class="keyword">int</span> pageSize)</span></span>;</span><br></pre></td></tr></table></figure>
<p>接口实现类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> PageResult <span class="title">getAll</span><span class="params">(<span class="keyword">int</span> pageNum, <span class="keyword">int</span> pageSize)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//将参数传给这个方法就可以实现物理分页了，非常简单。</span></span><br><span class="line">    PageHelper.startPage(pageNum, pageSize);</span><br><span class="line">    List&lt;UserEntity&gt; users = userMapper.getAll();</span><br><span class="line">    PageInfo&lt;UserEntity&gt; pageInfo = <span class="keyword">new</span> PageInfo&lt;&gt;(users);</span><br><span class="line">    <span class="keyword">return</span> PageUitls.getPageResult(pageInfo);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样改写后，返回体就简洁许多了：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  "pageNum": 1,</span><br><span class="line">  "pageSize": 2,</span><br><span class="line">  "totalSize": 3,</span><br><span class="line">  "totalPages": 2,</span><br><span class="line">  "content": [</span><br><span class="line">    &#123;</span><br><span class="line">      "id": 1,</span><br><span class="line">      "userName": "Michael翔",</span><br><span class="line">      "passWord": "123",</span><br><span class="line">      "userSex": "MAN",</span><br><span class="line">      "nickName": "ZX"</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      "id": 2,</span><br><span class="line">      "userName": "HQH",</span><br><span class="line">      "passWord": "123",</span><br><span class="line">      "userSex": "WOMAN",</span><br><span class="line">      "nickName": "QQ"</span><br><span class="line">    &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="IN-查询"><a href="#IN-查询" class="headerlink" title="IN 查询"></a>IN 查询</h2><p>关于 MyBatis 的 IN 查询，也是试验了很久，才 OK 的。 StackOverflow 上就有类似的问题 <a href="https://stackoverflow.com/questions/3428742/how-to-use-annotations-with-ibatis-mybatis-for-an-in-query" target="_blank" rel="noopener">How to use Annotations with iBatis (myBatis) for an IN query?</a>。</p>
<p>为了测试 MyBatis IN 查询，我们将之前的根据 ID 查询用户信息的接口进行修改，让它支持根据输入的 ID 列表查询多用户信息。</p>
<p>controller：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@ApiOperation</span>(value = <span class="string">"查询指定 ID 的用户"</span>, notes = <span class="string">"根据用户 id 列表查询其信息"</span>)</span><br><span class="line"><span class="meta">@ApiImplicitParam</span>(name = <span class="string">"ids"</span>, value = <span class="string">"用户 id 列表"</span>, paramType = <span class="string">"path"</span>, required = <span class="keyword">true</span>)</span><br><span class="line"><span class="meta">@GetMapping</span>(value = <span class="string">"/user/&#123;ids&#125;"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> PageResult <span class="title">getUser</span><span class="params">(@RequestParam(name = <span class="string">"pageNum"</span>, defaultValue = <span class="string">"1"</span>, required = <span class="keyword">false</span>)</span> <span class="keyword">int</span> pageNum,</span></span><br><span class="line"><span class="function">                          @<span class="title">RequestParam</span><span class="params">(name = <span class="string">"pageSize"</span>, defaultValue = <span class="string">"2"</span>, required = <span class="keyword">false</span>)</span> <span class="keyword">int</span> pageSize,</span></span><br><span class="line"><span class="function">                          @PathVariable String ids) </span>&#123;</span><br><span class="line">    List&lt;String&gt; idLst = Arrays.asList(ids.split(<span class="string">","</span>));</span><br><span class="line">    PageResult user = userService.getUserById(pageNum, pageSize, idLst);</span><br><span class="line">    <span class="keyword">return</span> user;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里有个小注意点，<code>@ApiImplicitParam</code> 注解中的 <code>paramType = &quot;path&quot;</code> 记得修改为 <code>path</code>，因为请求参数中包含路径变量了，否则渲染 URL 时，会出问题。</p>
<p>mapper 类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Select</span>(&#123;</span><br><span class="line">        <span class="string">"&lt;script&gt;"</span>,</span><br><span class="line">        <span class="string">"SELECT * "</span>,</span><br><span class="line">        <span class="string">"FROM users WHERE id IN"</span>,</span><br><span class="line">        <span class="string">"&lt;foreach item='id' index='index' collection='ids' open='(' separator=',' close=')'&gt;"</span>,</span><br><span class="line">        <span class="string">"#&#123;id&#125;"</span>,</span><br><span class="line">        <span class="string">"&lt;/foreach&gt;"</span>,</span><br><span class="line">        <span class="string">"&lt;/script&gt;"</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="function">List&lt;UserEntity&gt; <span class="title">getUserById</span><span class="params">(@Param(<span class="string">"ids"</span>)</span> List&lt;String&gt; ids)</span>;</span><br></pre></td></tr></table></figure>
<p>说明：</p>
<ul>
<li><code>item</code> 标识集合中每一个元素进行迭代是的别名，很多教程中设置为 <code>item</code>，我这里改为 <code>id</code> 也是 OK，而且也易于理解；</li>
<li><code>index</code> 指定一个名字，用于表示在迭代过程中，每次迭代到的位置，从 0 开始；</li>
<li><code>open</code> 表示该语句以什么开始；</li>
<li><code>separator</code> 表示在每次进行迭代之间以什么符号作为分隔符；</li>
<li><code>close</code> 表示以什么结束；</li>
<li><code>collection</code> 属性，该属性是必须指定的，但是在不同情况下，该属性的值是不一样的；</li>
<li><code>@Param</code> 的设置比较关键，相当于给其修饰的参数指定一个别名：<ul>
<li>使用 <code>@Param</code>，默认会和参数名同名，或者以注解传入的变量名为准。变量名将作为 <code>@Select</code> 中的可用参数，比如，我这里这样定义 <code>@Param(&quot;ids2&quot;) List&lt;String&gt; ids</code>，那么，<code>@Select</code> 中可用参数名将是 <code>ids2</code>，<code>collection</code> 也须定义为 <code>ids2</code>，否则会报错：<code>nested exception is org.apache.ibatis.binding.BindingException: Parameter &#39;list&#39; not found. Available parameters are [ids2, param1]</code>;</li>
<li>不使用 <code>@Param</code> 时，那么，此时 <code>collection</code> 需要定义为 <code>list</code>，否则会报错：<code>nested exception is org.apache.ibatis.binding.BindingException: Parameter &#39;list2&#39; not found. Available parameters are [collection, list]</code>;</li>
</ul>
</li>
</ul>
<p>上面的说明参考自 <a href="https://blog.csdn.net/aiyawalie/article/details/52954138" target="_blank" rel="noopener">mybatis查询sql中in条件使用(foreach)</a> ，没有找到官方文档支撑，待补充。</p>
<h2 id="动态-SQL"><a href="#动态-SQL" class="headerlink" title="动态 SQL"></a>动态 SQL</h2><p>待后续补充</p>
<ul>
<li><a href="https://blog.csdn.net/wangb_java/article/details/73657958" target="_blank" rel="noopener">spring boot(8)-mybatis三种动态sql</a></li>
<li><a href="https://blog.csdn.net/owen_william/article/details/51815506" target="_blank" rel="noopener">MyBatis注解应用之动态SQL语句</a></li>
</ul>
<h2 id="FAQ"><a href="#FAQ" class="headerlink" title="FAQ"></a>FAQ</h2><h3 id="MyBatis-中-和-的区别"><a href="#MyBatis-中-和-的区别" class="headerlink" title="MyBatis 中 # 和 $ 的区别"></a>MyBatis 中 # 和 $ 的区别</h3><ul>
<li><code>#{}</code> 解析为一个 JDBC 预编译语句（<code>Prepared Statement</code>）的参数标记符 <code>?</code>。<code>#{}</code> 是经过预编译的，是安全的。因为 SQL 语句已经预编译好了，传入参数的时候，不会重新生产 SQL 语句。</li>
<li><code>${}</code> 是非安全的，存在 SQL 注入风险。<code>${}</code> 将传入的数据都当成一个字符串，会对自动传入的数据加一个双引号。</li>
</ul>
<p>例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">select * from emp where ename = <span class="string">'用户名'</span></span><br></pre></td></tr></table></figure>
<p>如果使用 <code>${}</code>，用户名被传入例如<code>‘smith or 1 = 1’</code>，那无论 <code>ename</code> 是否匹配都能查到结果。</p>
<p>使用 <code>${}</code> 的情况，<code>order by</code>、<code>like</code> 语句只能用 <code>${}</code>,用 <code>#{}</code> 会多个 <code>&#39; &#39;</code> 导致 SQL 语句失效。此外动态拼接 SQL，模糊查询时也要用 <code>${}</code>。</p>
<p><a href="http://www.mybatis.org/mybatis-3/sqlmap-xml.html#Parameters" target="_blank" rel="noopener">MyBatis 官网 —— Parameters</a> 的例子值得阅读：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Select</span>(<span class="string">"select * from user where id = #&#123;id&#125;"</span>)</span><br><span class="line"><span class="function">User <span class="title">findById</span><span class="params">(@Param(<span class="string">"id"</span>)</span> <span class="keyword">long</span> id)</span>;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Select</span>(<span class="string">"select * from user where name = #&#123;name&#125;"</span>)</span><br><span class="line"><span class="function">User <span class="title">findByName</span><span class="params">(@Param(<span class="string">"name"</span>)</span> String name)</span>;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Select</span>(<span class="string">"select * from user where email = #&#123;email&#125;"</span>)</span><br><span class="line"><span class="function">User <span class="title">findByEmail</span><span class="params">(@Param(<span class="string">"email"</span>)</span> String email)</span>;</span><br></pre></td></tr></table></figure>
<p>上面的写法，可以直接使用如下替换：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Select</span>(<span class="string">"select * from user where $&#123;column&#125; = #&#123;value&#125;"</span>)</span><br><span class="line"><span class="function">User <span class="title">findByColumn</span><span class="params">(@Param(<span class="string">"column"</span>)</span> String column, @<span class="title">Param</span><span class="params">(<span class="string">"value"</span>)</span> String value)</span>;</span><br></pre></td></tr></table></figure>
<p>关于这个问题的讨论：</p>
<ul>
<li><a href="https://www.zhihu.com/question/26914370" target="_blank" rel="noopener">知乎——mybatis中的#和$的区别 ？最好能说的稍微详细点 谢谢</a></li>
<li><a href="https://blog.csdn.net/zymx14/article/details/78067452" target="_blank" rel="noopener">CSDN——mybatis中的#和$的区别</a></li>
</ul>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a href="http://www.mybatis.org/mybatis-3/sqlmap-xml.html" target="_blank" rel="noopener">官宣-MyBatis XML</a></li>
<li><a href="http://www.ityouknow.com/springboot/2016/11/06/spring-boot-mybatis.html" target="_blank" rel="noopener">纯洁的微笑-Spring Boot(六)：如何优雅的使用 Mybatis</a> 本文的主要参考文章之一，入门挺好</li>
<li><a href="https://blog.csdn.net/larger5/article/details/79616058" target="_blank" rel="noopener">CSDN-larger5-[增删改查] SpringBoot + MyBatis（注解版）</a> 这位博主的示例，代码结构和风格都比较规范，值得学习</li>
<li><a href="https://blog.csdn.net/Winter_chen001/article/details/77249029" target="_blank" rel="noopener">CSDN-LuisChen的博客-Spring boot Mybatis 整合（完整版）</a></li>
<li><a href="https://www.cnblogs.com/linjiqin/p/9687491.html" target="_blank" rel="noopener">博客园-Ruthless-SpringBoot+Mybatis+Pagehelper分页</a> 查询结果关系映射那块，该文章介绍的 <code>@ResultMap</code> 比较方便；</li>
</ul>
<p>分页</p>
<ul>
<li><a href="https://bbs.csdn.net/topics/380003476" target="_blank" rel="noopener">CSDN——分页查询效率为什么高？</a> 关于分页的讨论</li>
<li><a href="https://blog.csdn.net/kingboyworld/article/details/78948304" target="_blank" rel="noopener">CSDN-SpringBoot使用Mybatis注解开发教程-分页-动态sql</a> 分页参考</li>
<li><a href="https://www.cnblogs.com/xifengxiaoma/p/11027551.html" target="_blank" rel="noopener">博客园-朝雨忆轻尘-Spring Boot：实现MyBatis分页</a> 推荐，<code>PageResult</code> 的优化，参考此文</li>
<li><a href="https://pagehelper.github.io/docs/howtouse/" target="_blank" rel="noopener">PageHelper-官宣-如何使用分页插件</a></li>
<li><a href="https://www.liaoxuefeng.com/wiki/1177760294764384/1217864791925600" target="_blank" rel="noopener">廖雪峰——分页查询</a></li>
</ul>
<p>FAQ</p>
<ul>
<li><a href="https://zhuanlan.zhihu.com/p/47416328" target="_blank" rel="noopener">知乎——这也许是你不曾留意过的 Mybatis 细节</a></li>
</ul>

      
    </div>

    
      

  <div class="popular-posts-header">相关文章</div>
  <ul class="popular-posts">
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/2019/07/07/java-spring-boot-hello-world/" rel="bookmark">Spring Boot 实战 —— 入门</a></div>
      
    </li>
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/2019/08/10/java-spring-boot-log4j2/" rel="bookmark">Spring Boot 实战 —— 日志框架 Log4j2 SLF4J 的学习</a></div>
      
    </li>
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/2019/07/13/java-generic/" rel="bookmark">Java 泛型知识笔记</a></div>
      
    </li>
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/2019/08/09/java-spring-boot-logback/" rel="bookmark">Spring Boot 实战 —— 日志框架 logback 的学习</a></div>
      
    </li>
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/2019/08/11/java-spring-boot-sentry-log4j2/" rel="bookmark">Spring Boot 实战 —— 通过 Sentry 收集 Log4j2 异常日志记录</a></div>
      
    </li>
  
  </ul>


    

    
    
    

    
      <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center;">
  <img id="wechat_subscriber_qcode" src="/images/wechat-qcode.jpg" alt="Michael翔 wechat" style="width: 200px; max-width: 100%;">
  <div>欢迎订阅 ヾﾉ≧∀≦)o</div>
</div>

    

    
      
    
    
      <div>
        <div id="reward-container">
  <div>我知道是不会有人点的，但万一有人想不开呢👇</div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">

    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/wechatpay.jpg" alt="Michael翔 微信支付">
        <p>微信支付</p>
      </div>
    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/alipay.png" alt="Michael翔 支付宝">
        <p>支付宝</p>
      </div>
    

  </div>
</div>

      </div>
    

    
      <div>
        




  



<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Michael翔</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    
    <a href="https://michael728.github.io/2019/07/20/java-spring-boot-mybatis/" title="Spring Boot 实战 —— MyBatis（注解版）使用方法">https://michael728.github.io/2019/07/20/java-spring-boot-mybatis/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Java/" rel="tag"># Java</a>
          
            <a href="/tags/Spring-Boot/" rel="tag"># Spring Boot</a>
          
            <a href="/tags/Data-Base/" rel="tag"># Data Base</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/07/14/java-spring-boot-swagger/" rel="next" title="Spring Boot 实战 —— 集成 Swagger 生成 RESTful API 文档">
                <i class="fa fa-chevron-left"></i> Spring Boot 实战 —— 集成 Swagger 生成 RESTful API 文档
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/08/03/linux-manjaro-install/" rel="prev" title="Manjaro 安装体验小结">
                Manjaro 安装体验小结 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8yODgyMC81Mzkw" "></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/logo.jpg" alt="Michael翔">
            
              <p class="site-author-name" itemprop="name">Michael翔</p>
              <div class="site-description motion-element" itemprop="description">DevOps CICD Blog 持续学习</div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">82</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">19</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">95</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/Michael728" title="GitHub &rarr; https://github.com/Michael728" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://weibo.com/1838446070/profile?topnav=1&wvr=6" title="微博 &rarr; https://weibo.com/1838446070/profile?topnav=1&wvr=6" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i>微博</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://www.cnblogs.com/michael-xiang/" title="博客园 &rarr; https://www.cnblogs.com/michael-xiang/" rel="noopener" target="_blank"><i class="fa fa-fw fa-globe"></i>博客园</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://www.zhihu.com/people/michaelXoX" title="知乎 &rarr; https://www.zhihu.com/people/michaelXoX" rel="noopener" target="_blank"><i class="fa fa-fw fa-globe"></i>知乎</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://twitter.com/728_michael" title="Twitter &rarr; https://twitter.com/728_michael" rel="noopener" target="_blank"><i class="fa fa-fw fa-twitter"></i>Twitter</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://t.me/michaelxiang" title="Telegram &rarr; https://t.me/michaelxiang" rel="noopener" target="_blank"><i class="fa fa-fw fa-telegram"></i>Telegram</a>
                </span>
              
            </div>
          

          
             <div class="cc-license motion-element" itemprop="license">
              
              
                
              
              
              
              <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
             </div>
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                关注列表
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://michael728.github.io/2018/09/16/blog-interesting/" title="https://michael728.github.io/2018/09/16/blog-interesting/">Blog List</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://zcheng.ren/posts/" title="https://zcheng.ren/posts/" rel="noopener" target="_blank">ZeeCoder</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://ehlxr.me/" title="https://ehlxr.me/" rel="noopener" target="_blank">ehlxr</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.kawabangga.com/" title="https://www.kawabangga.com/" rel="noopener" target="_blank">卡瓦邦噶-蚂蚁SRE</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://blog.stdioa.com/" title="https://blog.stdioa.com/" rel="noopener" target="_blank">David Dai</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://bestzuo.cn/" title="https://bestzuo.cn/" rel="noopener" target="_blank">Sanarous</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.zhyong.cn/" title="https://www.zhyong.cn/" rel="noopener" target="_blank">ZhangYong-爱折腾软件</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.dalaoyang.cn/" title="https://www.dalaoyang.cn/" rel="noopener" target="_blank">Dalaoyang-SpringBoot</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.wuliaole.com/index.html" title="http://www.wuliaole.com/index.html" rel="noopener" target="_blank">无聊小博</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://ilovey.live/" title="http://ilovey.live/" rel="noopener" target="_blank">低调小熊猫-Java开发</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://michael728.github.io/2016/09/03/blog-logfile/" title="https://michael728.github.io/2016/09/03/blog-logfile/">建站日志</a>
                  </li>
                
              </ul>
            </div>
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#简介"><span class="nav-number">1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#示例代码"><span class="nav-number">2.</span> <span class="nav-text">示例代码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#依赖"><span class="nav-number">3.</span> <span class="nav-text">依赖</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#配置"><span class="nav-number">4.</span> <span class="nav-text">配置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#代码"><span class="nav-number">5.</span> <span class="nav-text">代码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#分页"><span class="nav-number">6.</span> <span class="nav-text">分页</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#添加依赖"><span class="nav-number">6.1.</span> <span class="nav-text">添加依赖</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#分页配置"><span class="nav-number">6.2.</span> <span class="nav-text">分页配置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#代码变动"><span class="nav-number">6.3.</span> <span class="nav-text">代码变动</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#进一步"><span class="nav-number">6.4.</span> <span class="nav-text">进一步</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#IN-查询"><span class="nav-number">7.</span> <span class="nav-text">IN 查询</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#动态-SQL"><span class="nav-number">8.</span> <span class="nav-text">动态 SQL</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#FAQ"><span class="nav-number">9.</span> <span class="nav-text">FAQ</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#MyBatis-中-和-的区别"><span class="nav-number">9.1.</span> <span class="nav-text">MyBatis 中 # 和 $ 的区别</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考"><span class="nav-number">10.</span> <span class="nav-text">参考</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 – <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Michael翔</span>

  

  
</div>









        








        
      </div>
    </footer>

    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  



  
    
    
      
    
  
  <script color="0,0,255" opacity="0.5" zindex="-1" count="99" src="//cdn.jsdelivr.net/gh/theme-next/theme-next-canvas-nest@1.0.0/canvas-nest.min.js"></script>













  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.6/jquery.fancybox.min.js"></script>


  


  <script src="/js/utils.js?v=7.1.1"></script>

  <script src="/js/motion.js?v=7.1.1"></script>



  
  


  <script src="/js/affix.js?v=7.1.1"></script>

  <script src="/js/schemes/pisces.js?v=7.1.1"></script>




  
  <script src="/js/scrollspy.js?v=7.1.1"></script>
<script src="/js/post-details.js?v=7.1.1"></script>



  


  <script src="/js/next-boot.js?v=7.1.1"></script>


  

  

  

  


  
    <script>
  window.livereOptions = {
    refer: '2019/07/20/java-spring-boot-mybatis/'
  };
  (function(d, s) {
    var j, e = d.getElementsByTagName(s)[0];
    if (typeof LivereTower === 'function') { return; }
    j = d.createElement(s);
    j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
    j.async = true;
    e.parentNode.insertBefore(j, e);
  })(document, 'script');
</script>

  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
  

  
  

  


  

  

  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>


  

  

  

  

  

  
<script>
  $('.highlight').not('.gist .highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('复制成功');
        else $(this).text('复制失败');
      
      ta.blur(); // For iOS
      $(this).blur();
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('复制');
      }, 300);
    }).append(e);
  })
</script>


  

  

</body>
</html>
